﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ParkManagement
{
    /// <summary>
    /// 车辆应用服务类
    /// </summary>
    public class CarAppService : ApplicationService, ICarAppService
    {
        private readonly IAuthManager _authManager;
        private readonly CarManager _carManager;
        private readonly IRepository<Car, int> _carRepository;

        public CarAppService(
            JwtAuthManager authManager,
            CarManager carManager,
            IRepository<Car, int> carRepository)
        {
            _authManager = authManager;
            _carManager = carManager;
            _carRepository = carRepository;
        }

        // 添加
        public async Task<ActionResponse> CreateAsync(CreateCarDto input)
        {
            var userId = _authManager.GetUserId();
            CarType? carType = string.IsNullOrWhiteSpace(input.Type) ? null : (CarType)Enum.Parse(typeof(CarType), input.Type);
            await _carManager.CreateAsync(
                userId,
                input.PlateNo,
                carType);
            return ActionResponse.Successful();
        }

        // 更新
        public async Task<ActionResponse> UpdateAsync(UpdateCarDto input)
        {
            CarType? carType = string.IsNullOrWhiteSpace(input.Type) ? null : (CarType)Enum.Parse(typeof(CarType), input.Type);
            var car = await _carRepository.GetAsync(input.Id);
            car.SetPlateNo(input.PlateNo);
            car.SetType(carType);
            return ActionResponse.Successful();
        }

        // 我的
        public async Task<ListResponse<CarDto>> MyAsync(PagedListRequest request)
        {
            var userId = _authManager.GetUserId();
            // 数据筛选
            var query = _carRepository
                .Where(m => m.UserId == userId);
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Car>, List<CarDto>>(list);
            return ListResponse<CarDto>.Successful(count, dtos);
        }

        // 删除
        public async Task<ActionResponse> DeleteAsync(int id)
        {
            await _carRepository.DeleteAsync(id);
            return ActionResponse.Successful();
        }
    }
}